package com.mark.common.util.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

/**
 * 
 * @author Mark Liang
 * @category 完善 dbutil 方法
 * 
 */

public class BaseQueryRunner extends QueryRunner{
	
	public BaseQueryRunner(DataSource dataSource) {
		super(dataSource);
	}
	
	/**
	 * Execute a batch of SQL INSERT, UPDATE, or DELETE queries.
	 * 
	 * @param conn
	 *            The Connection to use to run the query. The caller is
	 *            responsible for closing this Connection.
	 * @param sql
	 *            The SQL to execute.
	 * @param params
	 *            An array of query replacement parameters. Each row in this
	 *            array is one set of batch replacement values.
	 * @return The number of rows updated per statement.
	 * @throws SQLException
	 *             if a database access error occurs
	 * @since DbUtils 1.1
	 */
	public int[] batch(Connection conn, String sql, Collection<Object[]> params)
			throws SQLException {

		PreparedStatement stmt = null;

		int[] rows = null;
		try {
			stmt = this.prepareStatement(conn, sql);

			for (Object[] param : params) {
				this.fillStatement(stmt, param);
				stmt.addBatch();
			}

			rows = stmt.executeBatch();

		} catch (SQLException e) {
			this.rethrow(e, sql, params.toArray());
		} finally {
			close(stmt);
		}
		
		return rows;
	}
	
	/**
	 * Execute a batch of SQL INSERT, UPDATE, or DELETE queries. The
	 * <code>Connection</code> is retrieved from the <code>DataSource</code> set
	 * in the constructor. This <code>Connection</code> must be in auto-commit
	 * mode or the update will not be saved.
	 * 
	 * @param sql
	 *            The SQL to execute.
	 * @param params
	 *            An list of query replacement parameters. Each row in this
	 *            array is one set of batch replacement values.
	 * @return The number of rows updated per statement.
	 * @throws SQLException
	 *             if a database access error occurs
	 * @since DbUtils 1.1
	 */
	public int[] batch(String sql, Collection<Object[]> params)
			throws SQLException {
		Connection conn = this.prepareConnection();

		try {
			return this.batch(conn, sql, params);
		} finally {
			close(conn);
		}
	}
	
	
	

}
